<?php

namespace app\index\controller;

use app\common\controller\Base;
use utils\Weixin\Jssdk;
use utils\Page\Page;
use think\Db;
use think\captcha\Captcha;
use think\Session;

/**
 * @title 用于建站
 */
class Index extends Base {

    /**
     * @title 网站首页
     */
    public function index() {

        // 网站开启状态
//        $site_status = config('base.site_status');
//        if (!$site_status) {
//            return config('base.title') . ' ' . config('base.site_url') .' 网站维护中...';
//        }

        $seo['title'] = config('base.title');
        $seo['keywords'] = config('base.keywords');
        $seo['description'] = config('base.description');
        $this->assign('seo', $seo);
        return view();
    }

    /**
     * @title 列表页面
     */
    public function lists_article() {


        $id = input('param.id', 0);

        $path = db('article_cat')->where('id', $id)->value('path');
        $cids = db('article_cat')->where('path', 'LIKE', '' . $path . '%')->column('id');


        $wheres = [];
        if ($id)
            $wheres['cid'] = ['in', $cids];



        $lists = model('article')->model_where($wheres)->order('recommend desc,listorder asc,id desc')->paginate(config('base.page_size'), false, ['query' => request()->get()]);
        $this->assign('lists', $lists);




        $count = model('article')->where($wheres)->count();

        // 分类信息
        $article_cat = db('article_cat')->where('id', $id)->find();
        $this->assign($article_cat);

        //  dd($lists);
        $page = new Page();


        if ($id)
            $url = my_url('index/index/lists_article?id=' . $id) . '?page={page}';
        else
            $url = my_url('index/index/lists_article') . '?page={page}';

        /* 如果是静态生成的话，需要开启这里
          if ($article_cat['alias']) {
          $url = '/' . $article_cat['alias'] . '/index_{page}.html';
          } else {
          $url = '/index_{page}.html';
          }

         */


        $page->setUrl($url);
        $page->setTotal($count);
        $page->setLimit(config('base.page_size'));

        $this->assign('pager', $page->render());



        $this->assign('seo', [
            'title' => $article_cat['title'],
            'keywords' => $article_cat['keywords'],
            'description' => $article_cat['description'],
        ]);
        //加载当前分类关联的 列表模板 
        if (isset($article_cat['tpl_lists'])) {
            return view($article_cat['tpl_lists']);
        } else {
            return view();
        }
    }

    /**
     * @title 搜索 
     */
    public function search_article() {
        $keyword = input('get.keyword', '');
        $lists = db('article')
                // ->where('cid', 'in', [])
                ->where('title|description', 'like', '%' . $keyword . '%')
                ->field('id,title as question,description as answer')
                ->select();
        $lists = array_out($lists);
        foreach ($lists as $key => $value) {
            $lists[$key]['link'] = my_url('index/index/views_article?id=' . $value['id']);
        }
        echo json_encode([
            'code' => 0,
            'msg' => '',
            'data' => $lists,
        ]);
    }

    /**
     * @title 文章详情页面
     */
    public function views_article($id) {

        empty($id) && $this->error('参数不能为空');

        $one = db('article')
                ->alias('a')
                ->join('article_cat ac', 'ac.id = a.cid', 'LEFT')
                ->where('a.id', $id)
                ->field('a.*,ac.alias as category_alias,ac.title as category_name')
                ->find();
        empty($one) && $this->error('没找到相关信息');

        // 单文章分页
        $rspage = array_filter(explode('<hr style="page-break-after:always;" class="ke-pagebreak" />', $one['content']));
        $page = new Page();
        $page->setUrl(url('index/index/views', ['id' => $id]));
        $page->setTotal(count($rspage));
        $page->setLimit(1);
        $one['page'] = $page->render();

        // 图集
        $one['albums'] = db('article_albums')->where('article_id', $id)->order('listorder')->column('image');
        $this->assign($one);

        //上一篇 & 下一篇        
        // $prev = Db::query('SELECT id, title FROM tb_article WHERE id = (SELECT max(id) FROM tb_article WHERE id < ?  AND cid=?   )  ', [$id, $one['cid']]);
        // $next = Db::query('SELECT id, title FROM tb_article WHERE id = (SELECT min(id) FROM tb_article WHERE id > ?  AND cid=?  ) ', [$id, $one['cid']]);


        $p_sql = 'SELECT m.id,m.title FROM ( SELECT ( @i := @i + 1 ) AS RowNum, A.* FROM tb_article A,( SELECT @i := 0 ) B  
	WHERE A.cid=?  ORDER BY A.recommend desc,A.listorder asc,A.id desc) m,
	(SELECT D.id,D.RowNum as n2 FROM
		( SELECT ( @j := @j + 1 ) AS RowNum,A.* FROM tb_article A,( SELECT @j := 0 ) B 
		WHERE A.cid=? ORDER BY A.recommend desc,A.listorder asc,A.id desc
		) D WHERE D.id = ? ) q WHERE m.RowNum > q.n2  limit  1 ';

        $n_sql = 'SELECT m.id,m.title FROM
	( SELECT ( @i := @i + 1 ) AS RowNum, A.* FROM tb_article A,( SELECT @i := 0 ) B  
	WHERE A.cid=?  ORDER BY A.recommend desc,A.listorder asc,A.id desc) m,(
	SELECT D.id,D.RowNum as n2 FROM
		( SELECT ( @j := @j + 1 ) AS RowNum,A.* FROM tb_article A,( SELECT @j := 0 ) B 
		WHERE A.cid=? ORDER BY A.recommend desc,A.listorder asc,A.id desc
		) D WHERE D.id = ? ) q WHERE m.RowNum < q.n2   order by m.RowNum desc limit  1';

        $prev = Db::query($p_sql, [$one['cid'], $one['cid'], $id]);
        $next = Db::query($n_sql, [$one['cid'], $one['cid'], $id]);

        $this->assign('prev', isset($prev[0]) ? $prev[0] : []);
        $this->assign('next', isset($next[0]) ? $next[0] : []);

        // SEO信息
        $this->assign('seo', [
            'title' => $one['title'],
            'keywords' => $one['keywords'],
            'description' => $one['description'],
        ]);

        // 如果文章本身绑定模板，则优化使用
        $tpl_views = '';
        if (!empty($one['tpl_views'])) {
            $tpl_views = $one['tpl_views'];
            return view($tpl_views);
        } else {
            $tpl_views = db('article_cat')->where('id', $one['cid'])->value('tpl_views');
            if ($tpl_views) {
                return view($tpl_views);
            } else {
                return '详情模板未指定';
            }
        }
    }

    /**
     * @title 商品列表页
     */
    public function lists_goods() {

        $id = input('param.id', 0);

        //empty($id) && $this->error('参数不能为空');


        $path = db('goods_cat')->where('id', $id)->value('path');
        $cids = db('goods_cat')->where('path', 'LIKE', '' . $path . '%')->column('id');

        $wheres = [];
        if ($id)
            $wheres['cid'] = ['in', $cids];
        if (request()->get('keyword'))
            $wheres['title'] = ['like', '%' . request()->get('keyword') . '%'];

        $lists = model('goods')->model_where($wheres)->order('recommend desc,listorder asc,id desc')->paginate(config('base.page_size'), false, ['query' => request()->get()]);


        $goods_cat = db('goods_cat')->where('id', $id)->find();
        $this->assign($goods_cat);


        $this->assign('lists', $lists);
        $this->assign('pager', $lists->render());

        $this->assign('seo', [
            'title' => $goods_cat['title'],
            'keywords' => $goods_cat['keywords'],
            'description' => $goods_cat['description'],
        ]);





        //加载当前分类关联的 列表模板 
        if (isset($goods_cat['tpl_lists'])) {
            return view($goods_cat['tpl_lists']);
        } else {
            return view();
        }
    }

    /**
     * @title 搜索 
     */
    public function search_goods() {
        $keyword = input('get.keyword', '');
        $lists = db('goods')
                // ->where('cid', 'in', [])
                ->where('title|description', 'like', '%' . $keyword . '%')
                ->field('id,title as question,description as answer')
                ->select();
        $lists = array_out($lists);
        foreach ($lists as $key => $value) {
            $lists[$key]['link'] = my_url('index/index/views_goods?id=' . $value['id']);
        }
        echo json_encode([
            'code' => 0,
            'msg' => '',
            'data' => $lists,
        ]);
    }

    /**
     * @title 商品详情页面
     */
    public function views_goods($id) {

        empty($id) && $this->error('参数不能为空');

        $one = db('goods')
                ->alias('a')
                ->join('goods_cat gc', 'gc.id = a.cid', 'LEFT')
                ->where('a.id', $id)
                ->field('a.*,gc.alias as category_alias,gc.title as category_name')
                ->find();
        empty($one) && $this->error('没找到相关信息');


        $extra_fields_arr = [];
        if ($one['smeta_json']) {
            $extra_fields_arr = json_decode($one['smeta_json'], true);
        }
        foreach ($extra_fields_arr as $key => $value) {
            $one[$key] = $value;
        }

        $this->assign($one);

        // 图集
        $albums = db('goods_albums')->where('goods_id', $id)->order('listorder')->column('image');
        $this->assign('albums', $albums);



        $this->assign('seo', [
            'title' => $one['title'],
            'keywords' => $one['title'],
            'description' => $one['title']
        ]);

        // 如果文章本身绑定模板，则优化使用
        $tpl_views = '';
        if (!empty($one['tpl_views'])) {
            $tpl_views = $one['tpl_views'];
            return view($tpl_views);
        } else {
            $tpl_views = db('goods_cat')->where('id', $one['cid'])->value('tpl_views');
            if ($tpl_views) {
                return view($tpl_views);
            } else {
                return '详情模板未指定';
            }
        }
    }

    /**
     * @title 留言反馈
     */
    public function feedback() {



        if (request()->isPost()) {

//            $ip = $_SERVER['HTTP_X_REAL_IP'] ?? $_SERVER['REMOTE_ADDR'];
//            if (session('?error.hits') && intval(session('error.hits')) >= 10) {
//                session('?error.expire') ?: session('error.expire', time());
//            }
//            if (session('?error.expire') && intval(session('error.expire')) - time() < 3600) {
//                // $this->error('你的操作有点频繁哦。请歇一会再来。。');
//            }

            if (!captcha_check(request()->post('captcha'))) {
                $this->error('验证码输错了');
            };

            $post = input('post.');

            // 商品的补充字段
            $smeta_arr = [];
            $extra_fields = config('feedback');
            if ($extra_fields && is_array($extra_fields)) {
                foreach ($extra_fields as $key => $value) {
                    $smeta_arr[$key] = $post[$key] ?? '';
                }
            }
            $data['smeta_json'] = json_encode($smeta_arr);
            $data['create_time'] = time();
            $data['ip'] = $_SERVER['HTTP_X_REAL_IP'] ?? $_SERVER['REMOTE_ADDR'];


            $insertId = db('feedback')->insertGetId($data);

            if ($insertId) {


//                $hits = session('?error.hits') ? session('error.hits') : 0;
//                session('error.hits', $hits + 1);


                $this->success('提交成功', '');
            } else {
                $this->error('反馈失败');
            }
        } else {
            
        }
    }

    /**
     * @title 点击数+1
     */
    public function hits_article() {
        $id = input('get.id', 0);
        if ($id) {
            $hits = db('article')->where('id', $id)->value('hits');
            db('article')->where('id', $id)->update([
                'hits' => intval($hits) + 1
            ]);
        }
    }

    /**
     * @title 点击数+1
     */
    public function hits_goods() {
        $id = input('get.id', 0);
        if ($id) {
            $hits = db('goods')->where('id', $id)->value('hits');
            db('goods')->where('id', $id)->update([
                'hits' => intval($hits) + 1
            ]);
        }
    }

}
